package com.magnate.software.jdk;

import org.junit.Assert;
import org.junit.Test;

import java.util.Optional;

/**
 * Optional例子
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2017/2/10 15:50
 */
public class OptionalExample {

    @Test
    public void optionalTest() {
        // null值的替代方式
        Optional<String> optional = Optional.of("optional");
        Assert.assertEquals("optional", optional.get());

        Optional emptyOptional = Optional.empty();
        Optional alsoEmpty = Optional.ofNullable(null);
        Assert.assertFalse(emptyOptional.isPresent());
        Assert.assertFalse(alsoEmpty.isPresent());

        Assert.assertTrue(optional.isPresent());

        Assert.assertEquals("1", emptyOptional.orElse("1"));
        Assert.assertEquals("2", emptyOptional.orElseGet(() -> "2"));
    }

}
